package gruppe7.data;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class UserController {

	private static final String USER_KEY = "user";
	private UserProvider provider;
	
	/* --- midlertidig kode begynd --- */
	private static UserController instance = null;
	
	public static UserController getInstance() {
		
		UserProvider up = null;
		
		try {
			up = new DBUserProvider();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// !!!! provider kan være null !!! 
		if (instance == null) instance = new UserController(up);
		
		return instance;
	}
	
	/* --- midlertidig kode slut --- */
	
	// skal være public, fix me */
	private UserController(UserProvider provider) {
		this.provider = provider;
	}
	
	public boolean doLogin(HttpServletRequest req, String username, String passwordClear) {
		PasswordHash hash = new PasswordHash(passwordClear);
		
		try { 
			// check om brugeren findes og sæt en Session-attribut hvis han gør
			User user = provider.authenticateUser(username, hash);
			req.getSession(true).setAttribute(USER_KEY, user);
			
			return true;
			
		}
		
		catch (UserException ue) {
			return false;
		}
	}
	
	public void doLogout(HttpServletRequest req) {
		if (req.getSession(false) != null) req.getSession().invalidate();
	}
	
	public boolean isValidSession(HttpServletRequest req) {
		HttpSession session = req.getSession(false);
		
		if (session == null || session.getAttribute(USER_KEY) == null) return false;
		
		else return true;
	}
	
	public User getSessionUser(HttpServletRequest req) {
		if (isValidSession(req)) return (User) req.getSession().getAttribute(USER_KEY);
		
		else return null;
	}
	
}
